package com.qianchang.microfinance.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mobstat.StatService;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.HttpBase;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.SharedPreferenceUtils;
import com.dm.library.utils.StringUtils;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.WelComeBean;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.AppManager;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;

import java.util.List;

import hei.permission.EasyPermissions;

/**
 * 版    权:  深圳市迪蒙网络科技有限公司
 * 描    述:  启动页
 * 修 改 人:  jiaohongyun
 * 修改时间:  2016/8/24
 */
public class SplashActivity extends BaseActivity {

    private static final String SPLASH_INDEX_URL = "splash_index_url";
    private static final String SPLASH_ANDROID_URL = "splash_android_url";

    private View view;

    private ImageView advImg;
    private TextView jumpBtn;

    private CountDownTimer mDownTimer;  //倒计时

    private boolean canJump = true;  //是否可以跳转
    private String advRedirectUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = View.inflate(this, R.layout.activity_splash, null);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(view);
        //点击安装包进行安装，安装结束后不点击完成，而是点击打开应用，应用启动后，再回到桌面，从桌面点击应用图标会造成反复重启应用的现象。
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            this.finish();
            return;
        }

//        stat();//初始化百度统计

        initView();
        initData();
        initListener();
        getSplashImg();

    }

    @Override
    protected void initView() {
        advImg = (ImageView) findViewById(R.id.advImg);
        jumpBtn = (TextView) findViewById(R.id.jumpBtn);

        // 防止第三方跳转时出现双实例
        Activity aty = AppManager.getAppManager().getActivity(MainActivity.class);
        if (aty != null && !aty.isFinishing()) {
            finish();
            return;
        }
        // 渐变展示启动屏
        AlphaAnimation aa = new AlphaAnimation(1.0f, 1.0f);
        aa.setDuration(4000);
        view.startAnimation(aa);
        aa.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationEnd(Animation arg0) {
                //注释掉原来迪蒙的 2018.1.5
//                if (canJump) {
//                    doRedirect(false);
//                }

                checkPerm();             //新增2018.1.5 跳转的时候判断是否有应用的权限

            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationStart(Animation animation) {
            }
        });
    }

    protected void initData() {
        String andUrl = SharedPreferenceUtils.get(SplashActivity.this, SPLASH_ANDROID_URL, "").toString();
        if (!TextUtils.isEmpty(andUrl)) {
            // 网络获取图片去
            Glide.with(this.getApplicationContext()).load(DMConstant.Config.BASE_URL + andUrl).listener(new RequestListener<String, GlideDrawable>() {
                @Override
                public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                    advImg.setVisibility(View.GONE);
                    jumpBtn.setVisibility(View.GONE);
                    return false;
                }

                @Override
                public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                    advImg.setVisibility(View.VISIBLE);
                    jumpBtn.setVisibility(View.VISIBLE);
                    return false;
                }
            }).placeholder(R.drawable.img_qidong).error(R.drawable.img_qidong).into(advImg);
        }

    }


    private void initListener() {
        jumpBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                    //注释掉原来迪蒙的 2018.1.5
//                canJump = false;
//                doRedirect(true);

                //以下新增2018.1.5 点击跳转的时候判断是否有应用的权限
                if (EasyPermissions.hasPermissions(SplashActivity.this, Permissions)) {
                    canJump = false;
                    doRedirect(true);
                }else{
                    EasyPermissions.requestPermissions(SplashActivity.this, getString(reSting), PERMISSION_REQUEST_CODE_INIT, Permissions);
                }
            }
        });

        advImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null != advRedirectUrl && FormatUtil.validateUrl(advRedirectUrl)) {  //跳转处理
                    startActivity(new Intent(SplashActivity.this, WelComeToUrlActivity.class).putExtra("url", advRedirectUrl));
                }
            }
        });
    }

    /***
     * 请求后台配置的启动页图片
     */
    private void getSplashImg() {
        HttpParams params = new HttpParams();
        params.put("id", 0);
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.FIND_APP_INDEX_SET, params, new RequestCallBack<WelComeBean>() {

            @Override
            public void onSuccess(JsonResult<WelComeBean> response) {
                if (response.isReqDataSuccess()) {
                    doAfterGetSplashInfo(response.getObject());
                } else {
                    doAfterGetSplashInfo(null);
                }
            }

            @Override
            public void onFailure(String msg) {
                doAfterGetSplashInfo(null);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    /***
     * 处理启动页数据
     *
     * @param splashInfoBean
     */
    @SuppressLint("HandlerLeak")
    private void doAfterGetSplashInfo(final WelComeBean splashInfoBean) {
        //应测试要求延迟一段时间显示后台配置的图片
        new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (null != splashInfoBean) {
                    final String indexUrl = splashInfoBean.getIndexUrl();
                    String andUrl = splashInfoBean.getAndUrl();
                    if (!StringUtils.isEmptyOrNull(indexUrl)) {
                        SharedPreferenceUtils.put(SplashActivity.this, SPLASH_INDEX_URL, indexUrl);
                    }
                    if (!StringUtils.isEmptyOrNull(andUrl)) {
                        SharedPreferenceUtils.put(SplashActivity.this, SPLASH_ANDROID_URL, andUrl);
                    }

                    if (!StringUtils.isEmptyOrNull(andUrl)) {
                        advImg.setVisibility(View.VISIBLE);
                        jumpBtn.setVisibility(View.VISIBLE);
                        Glide.with(SplashActivity.this.getApplicationContext())
                                .load(DMConstant.Config.BASE_URL + andUrl)
                                .placeholder(R.drawable.img_qidong)
                                .into(advImg);
                    } else {
                        advImg.setVisibility(View.GONE);
                        jumpBtn.setVisibility(View.VISIBLE);
                    }

                    if (!StringUtils.isEmptyOrNull(indexUrl) && (indexUrl.startsWith("http") || indexUrl.startsWith("https"))) {
                        advRedirectUrl = indexUrl;
                    }
                } else {
                    String androidUrl = (String) SharedPreferenceUtils.get(SplashActivity.this, SPLASH_ANDROID_URL, "");
                    String indexUrl = (String) SharedPreferenceUtils.get(SplashActivity.this, SPLASH_INDEX_URL, "");
                    if (!StringUtils.isEmptyOrNull(androidUrl)) {
                        advImg.setVisibility(View.VISIBLE);
                        jumpBtn.setVisibility(View.VISIBLE);
                        Glide.with(SplashActivity.this.getApplicationContext())
                                .load(DMConstant.Config.BASE_URL + androidUrl.replace("\\", "/"))
                                .placeholder(R.drawable.img_qidong)
                                .into(advImg);
                    } else {
                        advImg.setVisibility(View.GONE);
                        jumpBtn.setVisibility(View.VISIBLE);
                    }
                    if (!StringUtils.isEmptyOrNull(indexUrl) && (indexUrl.startsWith("http") || indexUrl.startsWith("https"))) {
                        advRedirectUrl = indexUrl;
                    }
                }
            }
        }.sendEmptyMessageDelayed(0, 500);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mDownTimer) {
            mDownTimer.cancel();
            mDownTimer = null;
        }
    }

    /**
     * 页面跳转处理
     */
    private void doRedirect(boolean isOnClick) {
        if ((Boolean) SharedPreferenceUtils.get(SplashActivity.this, SharedPreferenceUtils.getKeyOfFirstRun(DMApplication.getInstance().getVersion()), true)) {
            gotoWelcome();
        } else {
//            if (isOnClick) {
//                startActivity(new Intent(SplashActivity.this, MainActivity.class));
//                finish();
//            } else {
//                gotoMain();
//            }
            if (initCheckLogin()){
                gotoMain();
            }
        }
    }

    /**
     * 用户登陆检查
     */
    private boolean initCheckLogin(){
        HttpBase.LoginCheckListener listener = (HttpBase.LoginCheckListener) this;
        boolean isLogin = listener.checkLogin();
        if (!isLogin) {
            // 如果没有登录,跳转到登录页
            listener.goLogin();
            return false;
        }else{
            return true;
        }
    }


    /**
     * 跳转到指引页面
     */
    private void gotoWelcome() {
        startActivity(new Intent(this, GuideActivity.class));
        finish();
    }

    /**
     * 跳转到首页
     */
    private void gotoMain() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void setStatusBar() {
        //        super.setStatusBar();
    }


    /**
     * 新增权限 2018.1.5
     */
    static String[] Permissions = {
            Manifest.permission.CAMERA,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.READ_CALL_LOG,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_SMS,
            Manifest.permission.RECEIVE_SMS,
            Manifest.permission.GET_ACCOUNTS,
            Manifest.permission.READ_CALL_LOG,
            Manifest.permission.WRITE_CALL_LOG
    };
    final public static int PERMISSION_REQUEST_CODE_INIT = 123;

    private void checkPerm() {
        if (EasyPermissions.hasPermissions(this, Permissions)) {
            //已经获取到权限
            if (canJump) {
                doRedirect(false);
            }
        } else {
            EasyPermissions.requestPermissions(this, getString(reSting), PERMISSION_REQUEST_CODE_INIT, Permissions);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsAllGranted() {
        if (canJump) {
            doRedirect(false);
        }
        DMLog.i("onPermissionsAllGranted");
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
//        super.onPermissionsDenied(requestCode, perms);

        if (EasyPermissions.hasPermissions(this, Permissions)) {
            canJump = false;                // 2018.1.5新增
            doRedirect(true);

            DMLog.i("onPermissionsDenied");
        } else {
            finish();
            DMLog.i("onPermissionsDenied");
        }

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (EasyPermissions.hasPermissions(this, Permissions)) {
            canJump = false;                // 2018.1.5新增
            doRedirect(true);
        }else{
            finish();
        }
    }


    private void stat() {
        // 如果没有页面和事件埋点，此代码必须设置，否则无法完成接入
        // 设置发送策略，建议使用 APP_START
        // 发送策略，取值 取值 APP_START、SET_TIME_INTERVAL、ONCE_A_DAY
        // 备注，SET_TIME_INTERVAL与ONCE_A_DAY，如果APP退出或者进程死亡，则不会定时发送
        // 建议此代码不要在Application中设置，否则可能因为进程重启等造成启动次数高，具体见web端sdk帮助中心
        // StatService.setSendLogStrategy(this, SendStrategyEnum.APP_START, 1, false);

        // setSendLogStrategy已经@deprecated，建议使用新的start接口
        // 如果没有页面和自定义事件统计埋点，此代码一定要设置，否则无法完成统计
        // 进程第一次执行此代码，会导致发送上次缓存的统计数据；若无上次缓存数据，则发送空启动日志
        // 由于多进程等可能造成Application多次执行，建议此代码不要埋点在Application中，否则可能造成启动次数偏高
        // 建议此代码埋点在统计路径触发的第一个页面中，若可能存在多个则建议都埋点
        StatService.start(this);
        StatService.setDebugOn(true);

    }


}
